//
//  CityPositionViewController.m
//  MemberProject
//
//  Created by mac on 15/4/28.
//  Copyright (c) 2015年 MAC OS X. All rights reserved.
//

#import "CityPositionViewController.h"
#import "FirstCityPositionTableViewCell.h"
#import "SecondCityPositionTableViewCell.h"
#import <CoreLocation/CoreLocation.h>//定位API接口
@interface CityPositionViewController ()<UITableViewDelegate,UITableViewDataSource,CLLocationManagerDelegate>
@property(strong,nonatomic)NSDictionary *citys;

@property(strong,nonatomic)UITableView *firstTableView;
@property(strong,nonatomic)UITableView *secondTableView;
@property(strong,nonatomic)UITableView *thirdTabelView;
@property(strong,nonatomic)UITableView *extTableView;


@property(strong,nonatomic)NSArray *firstData;
@property(strong,nonatomic)NSArray *secondData;
@property(strong,nonatomic)NSArray *thirdData;
@property(strong,nonatomic)NSArray *extData;

@property(strong,nonatomic)CLLocationManager *locationManager;
@end

@implementation CityPositionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets=NO;
    
    self.title=@"城市列表";
    
    UIBarButtonItem *leftBarButton=[[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleBordered target:self action:@selector(chickLeftBarButton:)];
    self.navigationItem.leftBarButtonItem=leftBarButton;
    
    NSString *filePath=[[NSBundle mainBundle]pathForResource:@"city" ofType:@"json"];
    NSData *data=[[NSData alloc]initWithContentsOfFile:filePath];
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    self.citys=dic;
    
    
    UITableView *tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH/3, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    tableView.delegate=self;
    tableView.showsVerticalScrollIndicator=NO;
    tableView.dataSource=self;
    [self.view addSubview:tableView];
    self.firstTableView=tableView;
    [tableView registerNib:[UINib nibWithNibName:@"FirstCityPositionTableViewCell" bundle:nil] forCellReuseIdentifier:@"CellIdentifier"];
    NSMutableArray *arrM=[NSMutableArray array];
    [arrM addObject:@{@"p":@"GPS定位"}];
    [arrM addObjectsFromArray:self.citys[@"citylist"]];
    self.firstData=arrM;
    
    
    tableView=[[UITableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/3, 64, SCREEN_WIDTH/3, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    tableView.delegate=self;
    tableView.showsVerticalScrollIndicator=NO;
    tableView.dataSource=self;
    [self.view addSubview:tableView];
    self.secondTableView=tableView;
    tableView.hidden=YES;
    [tableView registerNib:[UINib nibWithNibName:@"FirstCityPositionTableViewCell" bundle:nil] forCellReuseIdentifier:@"CellIdentifier"];
    
    tableView=[[UITableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/3*2, 64, SCREEN_WIDTH/3, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
//    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    tableView.delegate=self;
    tableView.showsVerticalScrollIndicator=NO;
    tableView.dataSource=self;
    tableView.hidden=YES;
    [self.view addSubview:tableView];
    self.thirdTabelView=tableView;
    [tableView registerNib:[UINib nibWithNibName:@"SecondCityPositionTableViewCell" bundle:nil] forCellReuseIdentifier:@"CellIdentifier"];
    
    tableView=[[UITableView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/3, 64, SCREEN_WIDTH/3*2, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
//    tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    tableView.delegate=self;
    tableView.showsVerticalScrollIndicator=NO;
    tableView.dataSource=self;
    tableView.hidden=YES;
    [self.view addSubview:tableView];
    self.extTableView=tableView;
    [tableView registerNib:[UINib nibWithNibName:@"SecondCityPositionTableViewCell" bundle:nil] forCellReuseIdentifier:@"CellIdentifier"];
    
    
    //开启定位
    self.locationManager = [[CLLocationManager alloc] init];
    if ([CLLocationManager locationServicesEnabled]){
        NSLog(@"定位服务正常！");
//        _locationManager.desiredAccuracy = kCLLocationAccuracyBest; //定位的精确程度
//        _locationManager.distanceFilter = 100.0f; //距离过滤
//        _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        self.locationManager.delegate = self;//设置代理
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager startUpdatingHeading];//开启方向监测服务
        [self.locationManager startUpdatingLocation];//开启定位服务
    }else{
        NSLog(@"定位服务异常");
    }
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    /*<+23.13529539,+113.24969845> +/- 65.00m (speed -1.00 mps / course -1.00) @ 14-5-15 \U4e2d\U56fd\U6807\U51c6\U65f6\U95f410:05:39*/
    NSLog(@"locations = %@",locations);
    //Cllocation 对于位置的几个重要的属性 -经纬度的坐标信息(CLLocationCoordinate2D是个结构体，成员有CLLocationDegrees类型的经度和纬度），海拔（altitude）,水平和垂直精度（horizontalAccuracy and verticalAccuracy accuracy）方向（course-CLLocationDirection),速度（speed-CLLocationSpeed);
    CLLocation *cl = [locations lastObject];
    
    
    //解析现在的代码 ---叫位置的反编码 CLGeocoder
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:cl completionHandler:^(NSArray *placemarks, NSError *error) {
        //CLPlacemark --地理位置标记
        for (CLPlacemark *pm in placemarks){
            NSLog(@"%@",pm);
            NSLog(@"name = %@",pm.name);
            NSLog(@"addressDictionary = %@",pm.addressDictionary);
            NSLog(@"thoroughfare = %@",pm.thoroughfare);
            NSLog(@"locality = %@",pm.locality);
        }
    }];
    //停止位置的监测
    [_locationManager stopUpdatingLocation];
}

#pragma mark - tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(tableView==self.firstTableView){
        return self.firstData.count;
    }
    if(tableView==self.secondTableView){
        return self.secondData.count;
    }
    if(tableView==self.thirdTabelView){
        return self.thirdData.count;
    }
    if(tableView==self.extTableView){
        return self.extData.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier=@"CellIdentifier";
    if(tableView==self.firstTableView){
        FirstCityPositionTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.cityLabel.text=self.firstData[indexPath.row][@"p"];
        return cell;
    }
    if(tableView==self.secondTableView){
        FirstCityPositionTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.cityLabel.text=self.secondData[indexPath.row][@"n"];
        return cell;
    }
    if(tableView==self.thirdTabelView){
        SecondCityPositionTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.cityLabel.text=self.thirdData[indexPath.row][@"s"];
        return cell;
    }
    if(tableView==self.extTableView){
        SecondCityPositionTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
        cell.cityLabel.text=self.extData[indexPath.row][@"n"];
        return cell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView==self.firstTableView){
        if(indexPath.row==0){
            return;
        }
        self.secondData=self.firstData[indexPath.row][@"c"];
        NSDictionary *dic=[self.secondData lastObject];
        if(dic[@"a"]){
            //存在多级
            self.secondTableView.hidden=NO;
            self.thirdTabelView.hidden=YES;
            self.extTableView.hidden=YES;
            
            [self.secondTableView reloadData];
        }else{
            //不存在多级
            self.secondTableView.hidden=YES;
            self.thirdTabelView.hidden=YES;
            self.extTableView.hidden=NO;
            
            self.extData=self.firstData[indexPath.row][@"c"];
            [self.extTableView reloadData];
        }
        
        return;
    }
    if(tableView==self.secondTableView){
        self.thirdTabelView.hidden=NO;
        self.thirdData=self.secondData[indexPath.row][@"a"];
        [self.thirdTabelView reloadData];
        return;
    }
    if(tableView==self.thirdTabelView){
        return;
    }
    if(tableView==self.extTableView){
        return;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView==self.firstTableView){
        return 60;
    }
    if(tableView==self.secondTableView){
        return 60;
    }
    if(tableView==self.thirdTabelView){
        return 60;
    }
    if(tableView==self.extTableView){
        return 60;
    }
    return 0;
}
#pragma mark - LeftBarButton
-(void)chickLeftBarButton:(UIBarButtonItem *)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
